package state

import (
	"luu/number"
)

type luaValue interface{}

func TypeOf(val luaValue) LuaType {
	switch val.(type) {
	case nil:
		return LUA_TNIL
	case bool:
		return LUA_TBOOLEAN
	case int64:
		return LUA_TNUMBER
	case float64:
		return LUA_TNUMBER
	case string:
		return LUA_TSTRING
	case *LuaTable:
		return LUA_TTABLE
	case *closure:
		return LUA_TFUNCTION
	default:
		panic("todo lua type")
	}
}

func Obj2Float(val luaValue) (float64, bool) {
	switch x := val.(type) {
	case float64:
		return x, true
	case int64:
		return float64(x), true
	case string:
		return number.ParseFloat64(x)
	default:
		return 0, false
	}
}

func Obj2Integer(val luaValue) (int64, bool) {
	switch x := val.(type) {
	case int64:
		return x, true
	case float64:
		return number.FloatToInteger(x)
	case string: //可以先转换为浮点数，再转换为 int64
		if i, ok := number.ParseInt64(x); ok {
			return i, ok
		}
		if f, ok := number.ParseFloat64(x); ok {
			return number.FloatToInteger(f)
		}
		return number.ParseInt64(x)
	default:
		return 0, false
	}
}
